package com.xu.tools.model;

import org.springframework.http.HttpStatus;

import java.io.Serializable;

/**
 * @author xuguan
 * @date 2023/2/2
 * @desc 统一返回类
 */
public class Result<T> implements Serializable {

    private static final long serialVersionUID = -2679174778544913577L;

    private Integer code;
    private String msg;
    private T data;

    public Result() {
    }

    public Result(HttpStatus httpStatus, T data) {
        this.code = httpStatus.value();
        this.msg = httpStatus.getReasonPhrase();
        this.data = data;
    }

    public Result(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static <T> Result<T> ok(T data) {
        return new Result<>(HttpStatus.OK, data);
    }

    public static <T> Result<T> fail(HttpStatus httpStatus, T data) {
        return new Result<>(httpStatus, data);
    }

    public static <T> Result<T> fail(Integer code, String msg, T data) {
        return new Result<>(code, msg, data);
    }

    /**
     * 请求是否响应成功
     *
     * @return true:成功
     */
    public boolean ok() {
        return this.code.equals(HttpStatus.OK.value());
    }
}
